package com.ws.mbp.springsecuritydemo.utils;

import com.ws.mbp.springsecuritydemo.bean.Users;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Component
public class JwtUtils {
    //  密钥 这里替换为你生成的Base64密钥字符串 不能太短不安全
    @Value("${jwt.secret}")
    private String secret;
    // 过期时间（秒）
    @Value("${jwt.expiration}")
    private Long expiration;
    //  发布者
    @Value("${jwt.issuer:default-issuer}")
    private String issuer;

    // 从token中获取用户名
    public String extractUsername(String token) {
        return extractClaim(token, Claims::getSubject);
    }

    // 从token中获取用户ID
    public String extractUserId(String token) {
        return extractClaim(token, claims -> claims.get("userId", String.class));
    }

    // 从token中获取用户角色
    public List<String> extractRoles(String token) {
        return extractClaim(token, claims -> claims.get("roles", List.class));
    }

    // 从token中获取过期时间
    public Date extractExpiration(String token) {
        return extractClaim(token, Claims::getExpiration);
    }

    // 提取token中的单个声明
    public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
        final Claims claims = extractAllClaims(token);
        return claimsResolver.apply(claims);
    }

    // 解析token获取所有声明
    public Claims extractAllClaims(String token) {
        try {
            return Jwts.parserBuilder()
                    .setSigningKey(getSigningKey())
                    .requireIssuer(issuer)
                    .build()
                    .parseClaimsJws(token)
                    .getBody();
        } catch (ExpiredJwtException e) {
            throw new SecurityException("Token expired", e);
        } catch (UnsupportedJwtException | MalformedJwtException | SignatureException e) {
            throw new SecurityException("Invalid token", e);
        } catch (IllegalArgumentException e) {
            throw new SecurityException("Token claims string is empty", e);
        }
    }

    // 验证token是否过期
    private Boolean isTokenExpired(String token) {
        return extractExpiration(token).before(new Date());
    }

    // 生成标准token（包含用户名和角色）
//    public String generateToken(UserDetails userDetails) {
//        Map<String, Object> claims = new HashMap<>();
//        claims.put("roles", extractAuthorities(userDetails));
//
//        return createToken(claims, userDetails.getUsername());
//    }
    //包含除了密码所有用户信息
    public String generateToken(UserDetails userDetails) {
        Users user = (Users) userDetails;
        Map<String, Object> claims = new HashMap<>();
        claims.put("roles", extractAuthorities(user));
        claims.put("userId", user.getUserId());
        claims.put("userName", user.getUsername());
        claims.put("userAge", user.getUserAge());
        claims.put("userSex", user.getUserSex());
        return createToken(claims, user.getUsername());
    }

    // 生成自定义token（包含额外信息）
    public String generateToken(UserDetails userDetails, Map<String, Object> extraClaims) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("roles", extractAuthorities(userDetails));
        claims.putAll(extraClaims);
        return createToken(claims, userDetails.getUsername());
    }

    // 生成自定义token（指定subject和claims）
    public String generateToken(String subject, Map<String, Object> claims) {
        return createToken(claims, subject);
    }

    // 从UserDetails中提取角色信息
    private List<String> extractAuthorities(UserDetails userDetails) {
        return userDetails.getAuthorities().stream()
                .map(GrantedAuthority::getAuthority)
                .collect(Collectors.toList());
    }

    // 创建token
    private String createToken(Map<String, Object> claims, String subject) {
        return Jwts.builder()
                .setClaims(claims)//信息 名 性别  年龄  id
                .setSubject(subject) // 设置主题（用户的唯一标识）
                .setIssuer(issuer)
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + expiration * 1000))
                .signWith(getSigningKey(), SignatureAlgorithm.HS256)
                .compact();
    }

    // 验证token
    public Boolean validateToken(String token, UserDetails userDetails) {
        final String username = extractUsername(token);
        return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
    }

    // 验证token（自定义验证逻辑）
    public Boolean validateToken(String token, Function<Claims, Boolean> validationFunction) {
        Claims claims = extractAllClaims(token);
        return validationFunction.apply(claims);
    }

    // 获取签名密钥
    private Key getSigningKey() {
        return Keys.hmacShaKeyFor(secret.getBytes());
    }
    public Boolean validateToken(String token) {
        try {
            extractAllClaims(token); // 解析并验证签名
            return !isTokenExpired(token); // 检查是否过期
        } catch (JwtException | IllegalArgumentException e) {
            // token 不合法或解析失败
            return false;
        }
    }
    // 刷新token
    public String refreshToken(String token) {
        final Claims claims = extractAllClaims(token);
        return createToken(claims, claims.getSubject());
    }
    // 从 JWT 中提取角色信息
    public List<SimpleGrantedAuthority> extractAuthorities(String token) {
        Claims claims = extractAllClaims(token);
        List<String> roles = claims.get("roles", List.class);

        return roles.stream()
                .map(SimpleGrantedAuthority::new)  // 添加 ROLE_ 前缀
                .collect(Collectors.toList());
    }

    // 生成Token（自定义用户信息）
//    public String generateToken(Users user) {
//        Map<String, Object> claims = new HashMap<>();
//        claims.put("userId", user.getUserId().toString());        // 用户ID
//        claims.put("username", user.getUsername());// 用户名
//        claims.put("roles", user.getRoles());      // 用户角色
//        claims.put("age", user.getUserAge());      // 年龄）
//        return createToken(claims, user.getUserId().toString());
//    }

}
